package com.jml.蚂蚁.netty.String序列化server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author:jml
 * @date: 2019/12/24 10:17
 * @description：Netty服务端
 */
public class NettyServer {
	
	private static int inetPort = 8080;
	
	 public static void main(String[] args) throws InterruptedException {
		 //创建Netty服务端的时候会创建两个线程池
		 // boss线程池 负责接受我们的请求
		 NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		 // 工作线程池 处理我们请求读写操作
		 NioEventLoopGroup workGroup = new NioEventLoopGroup();
		 // 创建我们的serverBootstrap
		 ServerBootstrap serverBootstrap = new ServerBootstrap();
		 serverBootstrap = serverBootstrap.group(bossGroup, workGroup);
		 //NioServerSocketChannel标记当前为服务器端
		 serverBootstrap = serverBootstrap.channel(NioServerSocketChannel.class);
		 //服务端处理客户端的数据，监听SocketChannel
		 serverBootstrap = serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			 @Override
			 protected void initChannel(SocketChannel ch) throws Exception {
				 //服务端处理每个请求的Handler
				 //ch.pipeline().addLast(new StringEncoder());
				 ch.pipeline().addLast(new StringDecoder());
				 ch.pipeline().addLast(new ServerHandler());
			 }
		 });
		 try {
			 //绑定端口号
			 //future表示future模式
			 ChannelFuture channelFuture = serverBootstrap.bind(inetPort);
			 channelFuture.sync();
			 System.out.println("服务器端启动成功:" + inetPort);
			 ////等待监听我们的请求
			 Channel channel = channelFuture.channel();
			 ChannelFuture channelFuture001 = channel.closeFuture();
			 channelFuture001.sync();
		 }catch (Exception e) {
			
		 }finally {
			 // 优雅的关闭我们的线程池
			 bossGroup.shutdownGracefully();
			 workGroup.shutdownGracefully();
		 }
	 }
}
